<template>
  <inject-template :item="item" :pageId="pageId" :popId="popId">
    <template v-slot:common>
      <div class="wb-form" @click.stop>
        <van-form @submit="onSubmit" @failed="onFailed">
          <div v-for="(item_, index) in formLists" :key="index">
            <div v-if="item_.type == FORM_TYPES_MAP.radio" :style="getFStyle(item_, index)" class="margin-top-30">
              <h4 v-html="getTitle(item_, index)"></h4>
              <van-radio-group v-model="wbFormValues[item_.tableKey]" @change="onChangeRadio">
                <van-radio v-for="(option, oindex) in item_.options" :key="'radio_' + oindex" :name="option" @click="onRelateClick(item_, oindex)">{{option}}</van-radio>
              </van-radio-group>
            </div>
            <div v-else-if="item_.type == FORM_TYPES_MAP.checkbox" :style="getFStyle(item_, index)" class="margin-top-30">
              <h4 v-html="getTitle(item_, index)"></h4>
              <van-checkbox-group v-model="wbFormValues[item_.tableKey]" :max="item_.max">
                <van-checkbox shape="square" v-for="(option, oindex) in item_.options" :key="'checkbox_' + oindex" :name="option">{{option}}</van-checkbox>
              </van-checkbox-group>
              <div v-if="item_.other" class="checkbox-other">
                <van-field type="text" v-model="wbFormValues[item_.other.tableKey]" :size="item_.length" :name="item_.other.tableKey" :placeholder="item_.other.placeholder" :border="true"/>
              </div>
            </div>
            <div v-else-if="item_.type == FORM_TYPES_MAP.dropdown" :style="getFStyle(item_, index)" class="margin-top-30">
              <h4 v-html="getTitle(item_, index)"></h4>
              <van-dropdown-menu>
                <van-dropdown-item v-model="dropdownValue" :options="item_.options"/>
              </van-dropdown-menu>
            </div>
            <div v-else-if="item_.type == FORM_TYPES_MAP.address" :style="getFStyle(item_, index)" class="margin-top-30">
              <h4 v-html="getTitle(item_, index)"></h4>
              <van-cell is-link @click="onShowPopup" :value="wbFormValues[item_.tableKey]"></van-cell>
              <van-popup v-model:show="isShowArea" position="bottom" :style="{ height: '50%' }">
                <van-area :area-list="areaList" ref="myArea" @change="onChangeArea" @confirm="onConfirm" @cancel="onCancel"/>
              </van-popup>
            </div>
            <div v-else-if="item_.type == FORM_TYPES_MAP.input || item_.type == FORM_TYPES_MAP.textarea" :style="getFStyle(item_, index)" class="margin-top-30">
              <h4 v-html="getTitle(item_, index)"></h4>
              <van-field :type="item_.type" v-model="wbFormValues[item_.tableKey]" :maxlength="item_.length" :name="item_.tableKey" autosize :placeholder="item_.placeholder" :border="false"/>
            </div>
          </div>
          <div class="margin-20 margin-top-50"><van-button round block type="info" native-type="submit" :style="btnStyles">提交</van-button></div>
        </van-form>
      </div>
    </template>
  </inject-template>
</template>

<script>
import { EventBus } from '@/store/index'
import { FORM_TYPES_MAP } from '@/common/const-form'
import AreaList from '@/components/form/js/area'
import InjectTemplate from '@/components/inject-template.vue'
import { utils } from '@/components/utils/utils'
import { wbBase } from '@/components/utils/wbBase'
import { reactive } from 'vue'

export default {
  name: "WbForm",
  mixins: [utils, wbBase],
  setup () {
    const state = reactive({
      wbFormValues: {},
      isShowArea: false,
      formLists: {},
    })
    const state_ = {
      dropdownValue: '',
      dropdownKey: '',
      FORM_TYPES_MAP: FORM_TYPES_MAP,
      areaList: AreaList,
      formValueNeeds: {},
    }
    _.merge(state, state_)
    return state
  },
  components: {
    InjectTemplate,
  },
  created(){
    this.setFormList();
  },
  computed: {
  },
  methods: {
    setFormList(){
      _.forEach(this.lists, (item) => {
        this.formValueNeeds[item.tableKey] = { isNeed: item.isNeed, name: item.name};
        this.setFormValues(item);
      })
      let arr = [];
      if(this.isH5Edit){
        this.formLists = this.lists;
      }else{
        _.forEach(this.lists, (item) => {
          if(item.relateId){
            arr.push(item);
          }
        })
        this.formLists = _.difference(this.lists, arr);
      }
      _.forEach(this.formLists, (formItem) => {
        if(formItem.type == FORM_TYPES_MAP.dropdown){
          let options_ = [];
          _.forEach(formItem.options, (option) => {
            options_.push({ text: option, value: option });
          })
          formItem.options = options_;
        }
      })
    },
    // 校验函数返回 true 表示校验通过，false 表示不通过
    phoneValidator(val) {
      return /1\d{10}/.test(val);
    },
    onSubmit(values) {
      if(this.isH5Edit){
        return
      }
      for(let key in values){
        if(this.formValueNeeds[key] && this.formValueNeeds[key].isNeed){
          if(!values[key]){
            this.showToast(this.formValueNeeds[key].name + "是必选项，请仔细查看后在提交！");
            return
          }
        }
      }
      this.wbFormValues[this.dropdownKey] = this.dropdownValue;
      let params_ = { data_str: JSON.stringify(this.wbFormValues), com_id: this.item.id};
      this.post("/Feact/formdata/", params_);
      EventBus.$emit("itemClick", {id: this.item.id, index: 0});
    },
    onFailed(errorInfo) {
      console.log('failed', errorInfo);
    },
    setFormValues(item){
      if(item.type == FORM_TYPES_MAP.address){
        this.wbFormValues[item.tableKey] = '选择需要显示的城市';
      }else if(item.type == FORM_TYPES_MAP.dropdown){
        this.dropdownValue = item.options[0];
        this.dropdownKey = item.tableKey;
        // this.wbFrmValues[item.tableKey] = item.options[0];
      }
      // else if(item.type == FORM_TYPES_MAP.checkbox){
      //   this.wbFormValues[item.tableKey] = item.options[0];
      // }else{
      // }
    },
    getFStyle(){
      return {
        color: this.item.styles.color,
        fontSize: this.item.styles.fontSize,
        textAlign: this.item.styles.textAlign,
      }
    },
    getTitle(item_, index){
      let title = (index+1) + '. ' + item_.name;
      if(item_.isNeed){
        title += '<span style="color:#f00">(*必填)</span>'
      }else{
        title += '<span style="color:#666">(可选填)</span>'
      }
      if(item_.type == "checkbox"){
        title += ' <span style="color:#666">(最多可选' + item_.max + ')</span>'
        if(item_.other){
          title += ' <span style="color:#f00">(字数限制为' + item_.other.length + '个)</span>'
        }
      }
      return title;
    },
    onRelateClick(item_, optionIndex){
      let relateItems = [];
      _.forEach(this.lists, (item) => {
        if(item.relateId){
          if(item.relateId == item_.id){
            relateItems.push(item);
          }
        }
      });

      if(relateItems.length > 0){
        let deleteArr = [];
        let lists = _.cloneDeep(this.lists);
        _.forEach(relateItems, (item) => {
          if(item.relateId){
            if(item.relateId == item_.id && item.optionIndex == optionIndex){
              //保留
            }else{
              //删除
              deleteArr.push(item);
            }
          }
        })
        this.formLists = _.differenceWith(lists, deleteArr, _.isEqual);
      }
    },
    onChangeRadio(value){
      this.currentValue = value;
    },
    onShowPopup() {
      this.isShowArea = true;
    },
    //value=0改变省，1改变市，2改变区
    //, arr, index
    onChangeArea(picker){
      let arr = picker.getValues();
      this.setAreaModel(arr);
    },
    //确定选择城市
    onConfirm(arr){
      this.isShowArea = false//关闭弹框
      this.setAreaModel(arr);
    },
    setAreaModel(arr){
      let areaName = '';
      for (var i = 0; i < arr.length; i++) {
        areaName = areaName + ( i == 0 ? '' : '/') + arr[i].name
      }
      this.wbFormValues[FORM_TYPES_MAP.address] = areaName;
    },
    //取消选中城市
    onCancel(){
      this.isShowArea = false;
      this.$refs.myArea[0].reset();// 重置城市列表
    }
  },
};
</script>

<style lang="scss">
.wb-form {
  width: inherit;
  height: inherit;

  .checkbox-other{
    .van-cell{
      border: var(--size-2) solid #c8c9cc;
      border-top: none;
    }
  }
  strong{
    text-align: center;
    color: #1ea0fa;
    display: inline-block;
    font-size: inherit;
  }
  .van-dropdown-item__option{
    text-align: center;
  }
  .van-radio-group, .van-checkbox-group{
    width: 100%;
    background-color: #fff;
    padding: 4px 8px;
  }
  .van-dropdown-menu{
    width: 100%;
    height: var(--size-80);
    border: none;
    outline: none;
  }
  .van-hairline--top-bottom::after, .van-hairline-unset--top-bottom::after{
    border: none;
  }
  h4{
    font-size: var(--size-30);
    text-align: left;
    margin-bottom: var(--size-10);
    font-size: inherit;
  }
  .van-radio__label{
    font-size: inherit;
  }
  .van-radio, .van-checkbox {
    margin-bottom: var(--size-8);
  }
  .van-checkbox__icon .van-icon, .van-radio__icon .van-icon{
    font-size: inherit;
    font-weight: inherit;
    font-style: inherit;
    width: inherit;
  }
}
</style>
